﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Sprout.Core.Extensions
{
    /// <summary>
    /// 字符串扩展
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// 转换字符串
        /// 空则返回空字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToEmpty(this string value)
        {
            return value == null ? string.Empty : value;
        }
        /// <summary>
        /// 转换字符串并删除左右空格
        /// 空则返回空字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToEmptyAndTrim(this string value)
        {
            if (value == null)
            {
                return string.Empty;
            }
            return value.Trim();
        }
        /// <summary>
        /// 根据正则提取开始和结束字符之间的关联词
        /// </summary>
        /// <param name="value">内容</param>
        /// <param name="begin">开始符</param>
        /// <param name="end">结束符</param>
        /// <param name="contain">是否包含开始符和结束符</param>
        /// <returns></returns>
        public static List<string> ExtractKeywordList(this string value, string begin, string end, bool contain = true)
        {
            string pattern = string.Format("[{0}].*?[{1}]", begin, end);
            MatchCollection mc = Regex.Matches(value, pattern);
            List<string> list = new List<string>();
            foreach (Match match in mc)
            {
                var v = match.ToString();
                if (!contain)
                {
                    v = v.TrimStart(begin.ToCharArray());
                    v = v.TrimEnd(end.ToCharArray());
                }
                list.Add(v);
            }
            return list;
        }
    }
}
